<template>
  <div class="dropdown" v-if="spaces.length >= 2">
    <!-- v-if="this.spaces.length > 0" -->
    <div class="dropbtn" @click="showSpaces()">
      <span>{{ space.name }}</span><span class="material-icons">expand_more</span>
    </div>
    <ul class="dropdown-content" v-show="display">
      <li v-for="(item, index) in spaces" :key="index" @click="handleSelected(index)">{{ item.name }}
        <span v-show="space._id === item._id" class="material-icons selected-space">check</span></li>
    </ul>
  </div>
</template>

<script>
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'KmSpace',
  components: {},
  props: {
    spaces: {
      type: Array
    }
  },
  data () {
    return {
      display: false,
      space: {
        _id: ''
      }
    }
  },
  watch: {
    spaces () {
      if (this.$route.query.sid && this.$route.query.sid !== '') {
        this.space = this.spaces.filter(e => e._id === this.$route.query.sid)[0]
        console.log('a', this.space)
      } else {
        this.space = this.spaces[0]
        console.log('b', this.space)
      }
    }
  },
  computed: {},
  mounted () {
    // if (this.$route.query.sid && this.$route.query.sid !== '') {
    //   this.space = this.spaces.filter(e => e._id === this.$route.query.sid)
    // } else {
    //   this.space = this.spaces[0]
    // }
    // console.log('mounted', this.space)
  },
  methods: {
    showSpaces () {
      this.display = !this.display
    },
    handleSelected (index) {
      this.selected = index
      this.space = this.spaces[index]
      this.$emit('selected', this.space._id)
      this.display = false
      this.$router.push({
        path: '/km',
        query: {
          id: this.space.homepageId,
          sid: this.space._id
        }
      })
    }
  }
})

</script>

<style lang="scss">
/* 容器 <div> - 需要定位下拉内容 */
.dropdown {
  position: relative;
  display: inline-block;
  width: 100%;
  height: 32px;
}

/* 下拉按钮样式 */
.dropbtn {
  background-color: $c3;
  color: white;
  font-size: 16px;
  border: none;
  cursor: pointer;
  height: inherit;
  width: inherit;
  text-align: center;
  line-height: 32px;
}

/* 下拉内容 (默认隐藏) */
.dropdown-content {
  z-index: 10;
  margin: 0 15%;
  display: none;
  position: absolute;
  background-color: #f8f9fa;
  width: 70%;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  min-height: 100px;
}

/* 下拉菜单的链接 */
.dropdown-content li {
  color: black;
  padding: 12px 50px;
  text-decoration: none;
  display: block;
}

/* 鼠标移上去后修改下拉菜单链接颜色 */
.dropdown-content li:hover {
  background-color: #f1f1f1
}

/* 在鼠标移上去后显示下拉菜单 */
.dropdown:hover .dropdown-content {
  display: block;
}

/* 当下拉内容显示后修改下拉按钮的背景颜色 */
// .dropdown:hover .dropbtn {
//     background-color: #3e8e41;
// }

.selected-space {
  color: $c3;
  margin-left: 20px;
}
</style>
